package com.sunkyc.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.sunkyc.commons.entity.R;
import com.sunkyc.commons.exception.CustomerException;
import com.sunkyc.commons.annotation.LogRecord;
import com.sunkyc.framework.system.CacheKey.AuthroticationCacheKeys;
import com.sunkyc.framework.system.entity.LoginUser;
import com.sunkyc.framework.system.service.LoginService;
import com.sunkyc.framework.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Api(tags = "认证登录")
public class LoginController {
    private final LoginService loginService;

    private final RedisUtils redisUtils;

    @PostMapping("/weblogin")
    @ApiOperation("网页登录")
    @LogRecord
    public R<String> login(@RequestBody  LoginUser loginUser, HttpServletRequest request){

        if(StringUtils.isBlank(loginUser.getUserName())){
            throw new CustomerException("用户名不能为空");
        }else if(StringUtils.isBlank(loginUser.getPassword())){
            throw new CustomerException("密码不能为空");
        }
        captchaValidated(loginUser);
        // 验证码通过验证，删除缓存的验证码信息
        return R.ok("登录成功",loginService.webLogin(loginUser.getUserName(),loginUser.getPassword(),request));
    }


    @GetMapping("/logout")
    @ApiOperation("登录退出")
    public R<Void> logout(){
        StpUtil.checkLogin();
        return R.ok();
    }


    private void captchaValidated(LoginUser loginUser){
        if(StringUtils.isBlank(loginUser.getCaptchaCode()) || StringUtils.isBlank(loginUser.getCaptchaUuid())){
            throw new CustomerException("请检查验证码是否正确");
        }
        String cacheCode = redisUtils.getCacheObject(AuthroticationCacheKeys.CAPTHCA_CACHE_KEY + ":" + loginUser.getCaptchaUuid());
        if(StringUtils.isBlank(cacheCode)){
            throw new CustomerException("验证码超时，请重新获取再进行登录");
        }
        if(!cacheCode.equals(loginUser.getCaptchaCode())){
            throw new CustomerException("验证码错误,请重试");
        }
        redisUtils.deleteObject(AuthroticationCacheKeys.CAPTHCA_CACHE_KEY+":"+loginUser.getCaptchaUuid());
    }




}
